package com.ali.gulimall.product.exception;

import com.ali.common.Exception.BizCodeEnum;
import com.ali.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：ALi
 * @date ：Created in 2022/7/21 16:49
 * @description：集中异常处理类
 * @modified By：
 * @version: $
 */
@Slf4j
//@ResponseBody//为了使返回的结果是json格式
//@ControllerAdvice(basePackages = "com.ali.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.ali.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {


    @ExceptionHandler(MethodArgumentNotValidException.class)//标注处理异常的种类
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMessage())
                .put("data",errMap);
    }


    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {

        log.error("错误异常{}",throwable);

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }




}